package com.zzx.boot.servlet.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzx.boot.entity.dto.AddPost;
import com.zzx.boot.entity.table.*;
import com.zzx.boot.entity.vo.PostVo;
import com.zzx.boot.entity.vo.ShareVo;
import com.zzx.boot.entity.vo.SupportVo;
import com.zzx.boot.entity.vo.UserVo;
import com.zzx.boot.mapper.PostMapper;
import com.zzx.boot.servlet.*;
import com.zzx.boot.utils.DateTImeUtils;
import com.zzx.boot.utils.R;
import com.zzx.boot.utils.SecurityUtils;
import com.zzx.boot.utils.Transaction;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * @author tan
 * @version 1.0
 * @date 2023/7/8 20:22
 */
@Service
@RequiredArgsConstructor
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {


    @Resource
    @Lazy
    private UtilsService utilsService;
    private final ImageService imageService;
    private final Transaction transaction;
    private final UserService userService;

    @Override
    public R addTopic(AddPost post) {
        return transaction.submit(()->{
            Image image = imageService.getImageById(Long.valueOf(post.getImages().get(0)));
            String title = "";
            if(post.getContent().length()<30){
                title = post.getContent();
            }else {
                title = post.getContent().substring(0,30);
            }
            Post post1 = new Post(null, SecurityUtils.getUserId(),title,image.getUrl(),
                    post.getContent(),0,"广东广州",0,
                    DateTImeUtils.getDate(),
                    post.getPostClassId(),0L,
                    post.getIsopen());
            baseMapper.insert(post1);
            // 添加图片
            boolean b = utilsService.addImageByPost(post.getImages(),post1.getPostClassId());
            return R.success(null,"添加文章成功");
        });


    }

    @Override
    public PostVo getPostDetailById(Long id,Boolean b) {
        PostVo vo = new PostVo();
        // 获取文章列表
        Post post = baseMapper.selectById(id);

        getPostList(b, vo, post);
        return vo;
    }

    public void getPostList( Boolean b, PostVo vo, Post post) {
        // 通过用户id获取用户信息
        UserVo user = userService.getUserById(post.getUserId());
        // 通过文章id获取图片
        // 1. 通过文章id获取图片id
        List<Long> list = utilsService.getImagesByPostId(post.getId());
        BeanUtils.copyProperties(post, vo);
        vo.setId(post.getId().toString());
        vo.setUser(user);
        List<String> images = null;
        if(list.size()!=0&& b){
            // 2. 通过图片id获取图片
           images = imageService.listByIds(list).stream().map(item->item.getUrl()).collect(Collectors.toList());
           vo.setImages(images);
        }
        // 通过分享id获取文章详情
        if(post.getType()==1){
            Post share = baseMapper.selectById(post.getShareId());
            vo.setShare(new ShareVo(share.getId().toString(),share.getTitle(),share.getTitlepic()));
        }
        SupportVo support= utilsService.getByUser(SecurityUtils.isLogin()?SecurityUtils.getLoginUser():null,post.getId());;
        vo.setSupport(support);
    }

    @Override
    public List<PostVo> postByUserPage(Long userId, Long current) {
        // 通过话题id获取所有的文章id
        Page<Post> page = new Page<>(current,10);
        LambdaQueryWrapper<Post> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Post::getUserId,userId);
        baseMapper.selectPage(page, wrapper);
        // 查找所有文章
        List<PostVo> collect = page.getRecords().stream().map(item -> {
            PostVo vo = new PostVo();
            this.getPostList(false,vo,item);
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<PostVo> postSearch(String keyword, Long current) {
        Page<Post> page = new Page<>(current,10);
        LambdaQueryWrapper<Post> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Post::getTitle,keyword);
        baseMapper.selectPage(page,wrapper);

        // 通过用户id查询顶踩记录
        // 判断是否登录状态
        Map<Long, SupportVo> supportMap = utilsService.getBetchByUser(SecurityUtils.isLogin()?SecurityUtils.getLoginUser():null);;


        List<PostVo> vos = page.getRecords().stream().map(item -> {
            PostVo vo = new PostVo();
            this.getPostList(false, vo, item);
            vo.setSupport(supportMap.get(item.getId()));
            return vo;
        }).collect(Collectors.toList());
        return vos;
    }

    @Override
    public List<PostVo> postByTopicPage(Long topicId, Long current) {
        // 通过话题id获取所有的文章id
        Page<Long> page = new Page<>(current,10);
        List<Long> postIds = utilsService.getPostIdByTopicId(page,topicId);

        // 查找所有文章
        List<PostVo> collect = postIds.stream()
                .map(item -> this.getPostDetailById(item,false)).collect(Collectors.toList());
        return collect;
    }





}
